-- local toolPrefix = "x86_64-elf-"
local toolPrefix = ""
local cflags = " -g -c -O0 -m32 -fno-pie -fno-stack-protector -nostdlib -nostdinc "
local gcc = toolPrefix.. "gcc"
local ld = toolPrefix.. "ld"
local objcopy = toolPrefix.. "objcopy"
local objdump = toolPrefix.. "objdump"
local readelf = toolPrefix.. "readelf"

target("a00", function ()
  set_kind("phony")
  add_deps("a00-boot", "a00-os")
  on_build(function(target)
    print("==============")
    os.exec("bximage -q -hd=16 -func=create -sectsize=512 -imgmode=flat disk.img")
    os.exec(ld.." -m elf_i386 -Ttext=0x7c00 build/boot.o build/os.o -o build/os.elf")
    os.exec(objcopy.." -O binary build/os.elf build/os.bin")
    -- os.exec(objdump.." -x -d -S  build/os.elf > build/os_dis.txt")
    -- os.exec(readelf.." -a  build/os.elf > build/os_elf.txt")
    os.exec("dd if=build/os.bin of=disk.img bs=512 seek=0 count=1 conv=notrunc")
  end)
end)

target("a00-boot", function ()
  set_kind("binary")
  add_files("src/boot.S")
  before_build(function (target)
    os.mkdir("build")
  end)
  on_build_files(function (target, sourcebatch, opt)
    local sources = table.concat(sourcebatch.sourcefiles, " ")
    os.exec(gcc..cflags.." -o build/boot.o "..sources)
  end)
  on_link(function (target)
  end)
end)

target("a00-os", function ()
  set_kind("binary")
  add_files("src/*.c")
  on_build_files(function (target, sourcebatch, opt)
    local sources = table.concat(sourcebatch.sourcefiles, " ")
    print("souces: %s", sources)
    os.exec(gcc..cflags.." -o build/os.o "..sources)
  end)
  on_link(function (target)
  end)
end)
